<?php 
class db{
	private $conn=NULL;
	private $serverInfo=array();
	public $affectRow=0;
	public $numRow=0;
	private $debugSettings=array();
	private $charset;
	private static $server_and_db=array();
	private $host='';
	private $db_name='';
	public function db($user,$pwd='',$host='127.0.0.1',$db_name,$_charset='utf8',$connectImediatly = false){
		$this->charset=$_charset;
		$this->serverInfo= array($host,$user,$pwd,$db_name);
		$this->db_name=$db_name;
		$this->host=$host;
		$this->server_and_db[$host][]=$db_name;
		if($connectImediatly){
			$this->doConnect();
		}
	}
	public function debugSetting($arr){
		$this->debugSettings = array_merge($this->debugSettings,$arr);
	}
	public function getConn(){
		return $this->conn;
	}
	private function microtime_float()
	{
		list($usec, $sec) = explode(" ", microtime());
		
		return ((float)$usec + (float)$sec);
	}
	private function logsql($sql,$type=1)
	{
		if(isset($this->debugSettings['log_file_name']))
		{
			$filename = $this->debugSettings['log_file_name'].'_'.date("mdHi").".txt";
		}else if($type==1){
			$filename = "slow_query_log_".date("mdHi").".txt";
		}else{			
			$filename = "special_log_".date("mdHi").".txt";
		}
		$handle = fopen($filename, 'a+');
		fwrite($handle, $sql."\r\n");
		fclose($handle);
	}
	private function doConnect($flag=false)
	{
		if($this->conn!=NULL)
		{
			if(!is_resource($this->conn)||@!mysql_query("SET NAMES ".$this->charset.';',$this->conn))
			{
				$flag=true;
			}
		}
		if($this->conn==NULL||$flag)
		{
			list($host,$user,$pwd,$db_name) = $this->serverInfo;
			if(is_resource($this->conn)||isset($this->conn)){
				mysql_close($this->conn);
				unset($this->conn);
			}
			$this->conn = mysql_connect($host,$user,$pwd,1) or die('A'.mysql_error());
			$this->doselect($db_name,$this->charset);			
		}
	}
	public function doselect($db_name,$charset='')
	{
		if(!is_resource($this->conn))$this->doConnect();
		if($charset=='') $charset=$this->charset;
		mysql_query('SET NAMES '.$charset.';',$this->conn) or die('C'.mysql_error());
		mysql_select_db($db_name,$this->conn) or die('B'.mysql_error());
		if($db_name=='rf_fixed_data_v1'){
			$this->query('select * from item');
			echo mysql_error();
		}
	}
	public function query($sql,$die=false){
		$this->doConnect();
		
		if(isset($this->debugSettings['slow_query'])&&$this->debugSettings['slow_query']>0)
		{
			$timestart = $this->microtime_float();
		}
		if($die)
			$rs = mysql_query($sql,$this->conn) or die("query Sql error:<br>".mysql_error()."<br>".$sql."<hr>");
		else
			$rs = mysql_query($sql,$this->conn);
		//echo curServer.'|'.$this->conn.'|'.$sql.'<br/>';
		//if()
		$echo = mysql_error();
		if($echo)die($echo."<br/>".$sql);
		if(!is_resource($rs)) return false;
		if(mysql_num_rows($rs)==0){
			if(mysql_affected_rows($this->conn)>0){
				$this->affectRow = mysql_affected_rows($this->conn);
			}else{
				return false;
			}
		}else{
			$this->numRow = mysql_num_rows($rs);
		}
		if(isset($this->debugSettings['slow_query'])&&$this->debugSettings['slow_query']>0)
		{
			$timeuse = $this->microtime_float()-$timestart;
			if($timeuse>$this->debugSettings['slow_query'])
			{
				$this->logsql($sql." -> ".$timeuse);
			}
		}
		if(isset($this->debugSettings['php_code'])&&eval($this->debugSettings['php_code']))
		{
			$this->logsql($sql);
		}
		return $rs;
	}
	public function execute($sql,$die=false)
	{
		$this->query($sql,$die);
	}
	public function lastId()
	{
		return mysql_insert_id($this->conn);
	}
	public function getFirst($sql,$die=false){
		$rs = $this->query($sql,$die);
		if($rs && ($one = mysql_fetch_row($rs)) ){
			return $one[0];
		}else{
			return false;
		}
	}
	public function getRow($sql,$die=false){
		$rs = $this->query($sql,$die);
		if($rs && ($one = mysql_fetch_assoc($rs)) ){
			return $one;
		}else{
			return false;
		}
	}	
	public function getRows($sql,$die=false,$limit=1000){
		$rs = $this->query($sql,$die);
		if(!$rs) return false;
		if($row = mysql_fetch_assoc($rs)){
			$one[] = $row;
			$ct=0;
			while($row = mysql_fetch_assoc($rs)){
				if($ct==$limit) break;
				$one[] = $row;
				$ct++;
			}
			return $one;
		}else{
			return false;
		}
	}
	public function exeMoreSql($sql,$limit=500){
		preg_match_all("/(select|show|update|delete|drop|create|alter|insert)\s+(([`'\"])[^`'\"]+\\3|[^;])+;?/i",$sql,$out,PREG_PATTERN_ORDER );
		if(count($out[0])==0) echo "No sql<br/>";
		//$out[0][0]=$sql;
		$rtn=array();
		for($i=0;$i<count($out[0]);$i++){
			$sql = trim($out[0][$i]);
			if(substr(strtolower($sql),0,6)=='select'&&strpos($sql,"()")===false&&!preg_match("/limit \d+(,\d+)?$/i",$sql)){
				$sql = (substr($sql,-1)==";"?substr($sql,0,-1):$sql)." limit ".$limit;
			}
			$result = $this->query($sql);
			
			if(mysql_num_rows($result)==0){
				if(mysql_affected_rows($this->conn)>0){
					$rtn[$i]['affected_rows'] = mysql_affected_rows($this->conn);
				}
				$rtn[$i]['data'] = array();
				$rtn[$i]['fileds'] = array();
				$rtn[$i]['num_rows'] = 0;
				continue;
			}else{
				$rtn[$i]['affected_rows'] = 0;
				$rtn[$i]['num_rows'] = mysql_num_rows($result);
			}
			
			$tmp = array();
			$fileds = array();
			while ($row = mysql_fetch_assoc($result)) {
				if(empty($fileds)){					
					foreach($row as $k=>$v){
						$fileds[]= $k;
					}					
				}
				$tmp[] = $row;
			}
			$rtn[$i]['data'] = $tmp;
			$rtn[$i]['fileds'] = $fileds;
			@mysql_free_result($result);
		}
		return $rtn;
	}
	public function moreSqlResult($arr,$headbgcolor='#003366',$headfontcolor='#ffffff'){
		$echo = "";
		foreach($arr as $v){
			$echo .= '<table border=1 >';
			$echo .= '<tr  bgcolor="'.$headbgcolor.'" style="color:'.$headfontcolor.'">';
			foreach($v['fileds'] as $k=>$v){
				$echo .= "<td>".$k."</td>";
			}
			$echo .= '</tr>';
			if($v['num_rows']>0){
				foreach($v['data'] as $kk=>$vv){
					$echo .= "<tr>";
					foreach($vv as $vvv)
					{
						$echo .= "<td>".$vvv."</td>";
					}
					$echo .= "</tr>";
				}
			}
			else if($v['affected_rows']>0)
			{
				$echo .= "<tr>";
				$echo .= "<td>Affected rows: ".$v['affected_rows'].".</td>";
				$echo .= "</tr>";
			}else{
				$echo .= "<tr>";
				$echo .= "<td>No data, no result!</td>";
				$echo .= "</tr>";
			}
			$echo .= '</table>';
		}
		return $echo;
	}
	function __destruct() {
		if($this->conn!=NULL&&is_resource($this->conn)){
			mysql_close($this->conn);
			unset($this->conn);
			$this->conn=NULL;
		}
	}
}
?>